package com.spice.im.preference;

import java.io.File;




import java.util.ArrayList;


//import java.util.Collection;
//import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
//import java.util.StringTokenizer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;




//import org.apache.http.NameValuePair;
//import org.apache.http.message.BasicNameValuePair;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.util.StringUtils;
//import org.jivesoftware.smackx.bookmark.BookmarkedConference;
import org.json.JSONArray;
//import org.json.JSONException;
import org.json.JSONObject;




































import cn.finalteam.galleryfinal.GalleryHelper;
import cn.finalteam.galleryfinal.GalleryImageLoader;
import cn.finalteam.galleryfinal.PhotoCropActivity;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import cn.finalteam.toolsfinal.BitmapUtils;
import cn.finalteam.toolsfinal.DateUtils;
import cn.finalteam.toolsfinal.DeviceUtils;
import cn.finalteam.toolsfinal.FileUtils;
import cn.finalteam.toolsfinal.Logger;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.speed.im.login.EncryptionUtil;
import com.spice.im.BaseDialog;
//import com.spice.im.ContactFrameActivity;
import com.spice.im.FlippingLoadingDialog;
import com.spice.im.Login;
import com.spice.im.OtherProfileActivity;
import com.spice.im.R;
import com.spice.im.RoundImageView;
import com.spice.im.SpiceApplication;
//import com.spice.im.ContactFrameActivity.exPhoneCallListener;
import com.spice.im.friend.SearchIQ;
import com.spice.im.friend.SearchIQResponse;
import com.spice.im.friend.SearchIQResponseProvider;
import com.spice.im.ui.HandyTextView;
import com.spice.im.utils.HeaderLayout;
import com.spice.im.utils.HeaderLayout.HeaderStyle;
import com.spice.im.utils.HeaderLayout.onRightImageButtonClickListener;
import com.spice.im.utils.ImageFetcher;
import com.spice.im.utils.TextUtils;
import com.spiceim.db.TContactGroup;
import com.spiceim.db.TContactGroupAdapter;
import com.stb.core.chat.ContactGroup;
import com.stb.core.uuid.DeviceUuidFactory2;
////import com.allen.ui.profile.ManagermentActivity;
//import com.allen.ui.profile.ProfileActivity;
//import com.allen.updateapk.DownloadApkThread;
//import com.allen.updateapk.HttpConnect;
//import com.allen.updateapk.VersionService;
//
//
//import com.stb.isharemessage.R;
import com.stb.isharemessage.service.aidl.IXmppFacade;
//import com.dodola.model.DuitangInfo;
import com.dodola.model.DuitangInfoAdapter;
//import com.example.android.bitmapfun.util.AsyncTask;
//import com.example.android.bitmapfun.util.ImageFetcher;
import com.example.android.bitmapfun.util.ObjectCache;
import com.stb.isharemessage.BeemApplication;
import com.stb.isharemessage.BeemService;
import com.stb.isharemessage.IConnectionStatusCallback;//网络状态相关
//import com.stb.isharemessage.service.Contact;
import com.stb.isharemessage.service.XmppConnectionAdapter;
//import com.stb.isharemessage.ui.register.BaseActivity;
//import com.stb.isharemessage.ui.register.BaseDialog;
//import com.stb.isharemessage.ui.register.FlippingLoadingDialog;
//import com.stb.isharemessage.ui.wizard.AccConfActivity;
//import com.stb.isharemessage.utils.BeemBroadcastReceiver;
import com.stb.isharemessage.utils.BeemConnectivity;
//import com.stb.isharemessage.utils.HeaderLayout;
//import com.stb.isharemessage.utils.TextUtils;
//import com.stb.isharemessage.utils.HeaderLayout.HeaderStyle;
//import com.stb.isharemessage.utils.HeaderLayout.onRightImageButtonClickListener;




































import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
//import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
//import android.widget.CheckedTextView;
import android.widget.CompoundButton;
//import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class PreferenceActivity extends Activity implements IConnectionStatusCallback,OnClickListener,OnCheckedChangeListener{

    private static final Intent SERVICE_INTENT = new Intent();

    static {
    	SERVICE_INTENT.setComponent(new ComponentName("com.spice.im", "com.stb.isharemessage.BeemService"));//自身应用pkg名称，非service所在pkg名称
    }
    private boolean mBinded = false;
    private IXmppFacade mXmppFacade;
    
    private Context mContext;
    
    private final ServiceConnection mServConn = new BeemServiceConnection();
    //  private final OnClickListener mOnClickOk = new MyOnClickListener();
//    private final BeemBroadcastReceiver mReceiver = new BeemBroadcastReceiver();//原来的网络状态注释掉
    private final OkListener mOkListener = new OkListener();
    private ContactGroup contact = null;
    public ImageFetcher mImageFetcher;
//    private List<ContactGroup> mListContact;
    private HashMap linkedList = new HashMap();
//    private RoundImageView imageView;
	private RoundImageView mIvUserPhoto;
	private LinearLayout mLayoutSelectPhoto;
	private LinearLayout mLayoutTakePicture;
	private Bitmap mUserPhoto;
	
	
	
    private String imgurl = null;
    private HandyTextView nickNameTextView;
    private String nickname;
    
    private LinearLayout user_item_layout_gender;
    private ImageView user_item_iv_gender;//性别
    private String sex;
    private HandyTextView ageTextView;
    private String age;
    
    private HandyTextView accountTextView;
    private String account; 
    private String JIDWithRes;
   
    private HandyTextView signTextView;
    private String sign; 
    
    protected TextView more_profile;
    private RelativeLayout more_profile2;
    
    private HeaderLayout mHeaderLayout;
    
    protected FlippingLoadingDialog mLoadingDialog;
    
    
    ToggleButton tb_offlinePin;//消息振动提示
    ImageButton ib_offlinePin;
    
    RelativeLayout rl_changeOfflinePin;//设置消息通知铃声
    RelativeLayout rl_verify_version;//检测新版本
    RelativeLayout rl_about_us;//关于我们
    
//    ToggleButton tb_p2p;//不显示离线用户
//    ImageButton ib_p2p;
//    ToggleButton tb_screenoff;//屏幕关闭修改状态
//    ImageButton ib_screenoff;
//    
//    
//    EditText et_screenoff_show_setting;//屏幕关闭状态签名
////    EditText et_serveraddr;//服务器地址
////    EditText et_serverport;//服务器端口
    
    private Button mCancelBt;
    
    private String mLogin = "";//just for ObjectCache prefix
    private SharedPreferences mSettings;
//    private Context mContext;
    
    
    private DuitangInfoAdapter duitangInfoAdapter = null;//用户信息存入本地数据库
    
    
	private String apkvercheck = "";
	public String downloadPrefix;
	
	private JSONArray array = null;
	private JSONObject object = null;
    private String apkversion = "";
    private String apkname = "";
    private String verdesc = "";
    private String mustupdateornot = "0";//0 false,1 true
    
    
    //网络状态start
	private View mNetErrorView;
	private TextView mConnect_status_info;
	private ImageView mConnect_status_btn;
    private exPhoneCallListener myPhoneCallListener = null;
    private TelephonyManager tm = null;
    //网络状态end
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
    	mSettings = PreferenceManager.getDefaultSharedPreferences(this);
    	String tmpJid = mSettings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "").trim();
//    	mLogin = StringUtils.parseName(tmpJid);
    	mLogin = tmpJid;
    	
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_preference);
        
        Properties props = new Properties();
        try {
            int id = this.getResources().getIdentifier("androidpn", "raw",
            		this.getPackageName());
            props.load(this.getResources().openRawResource(id));
        } catch (Exception e) {
//            Log.e(LOGTAG, "Could not find the properties file.", e);
            // e.printStackTrace();
        }
        apkvercheck = props.getProperty("apkvercheck", "");
        downloadPrefix = props.getProperty("downloadPrefix", "");
        
		mHeaderLayout = (HeaderLayout) findViewById(R.id.login_header);
		mHeaderLayout.init(HeaderStyle.TITLE_RIGHT_IMAGEBUTTON);
//		mHeaderLayout.setDefaultTitle("应用设置", null);
		
		mHeaderLayout.setTitleRightImageButton("应用设置", null,
				R.drawable.return2,
				new OnRightImageButtonClickListener());
		
		mLoadingDialog = new FlippingLoadingDialog(this, "请求提交中");
		
//		imageView = (RoundImageView) findViewById(R.id.headlogo); 
        mIvUserPhoto = (RoundImageView) findViewById(R.id.reg_photo_iv_userphoto);
		mLayoutSelectPhoto = (LinearLayout) findViewById(R.id.reg_photo_layout_selectphoto);
		mLayoutTakePicture = (LinearLayout) findViewById(R.id.reg_photo_layout_takepicture);
		mLayoutSelectPhoto.setOnClickListener(mOkListener);
		mLayoutTakePicture.setOnClickListener(mOkListener);
		
        nickNameTextView = (HandyTextView)findViewById(R.id.user_item_htv_name);  

        user_item_layout_gender = (LinearLayout)findViewById(R.id.user_item_layout_gender);
        user_item_iv_gender = (ImageView)findViewById(R.id.user_item_iv_gender);
        ageTextView = (HandyTextView)findViewById(R.id.user_item_htv_age); 
        
        accountTextView = (HandyTextView)findViewById(R.id.user_item_htv_account);

        signTextView = (HandyTextView)findViewById(R.id.user_item_htv_sign);

        
        more_profile = (TextView) findViewById(R.id.more_profile);
//        if(more_profile!=null)
        	more_profile.setOnClickListener(this);
        
        more_profile2 = (RelativeLayout) findViewById(R.id.more_profile2);
//        if(more_profile2!=null)
        	more_profile2.setOnClickListener(this);
		
        tb_offlinePin = (ToggleButton) findViewById(R.id.tb_offlinePin);
        tb_offlinePin.setOnCheckedChangeListener(this);
        ib_offlinePin = (ImageButton) findViewById(R.id.ib_offlinePin);
        
        rl_changeOfflinePin = (RelativeLayout) findViewById(R.id.rl_change_offline_pin);
        rl_changeOfflinePin.setOnClickListener(this);
        
        rl_verify_version = (RelativeLayout) findViewById(R.id.rl_verify_version);
        rl_verify_version.setOnClickListener(this);
        
        rl_about_us = (RelativeLayout) findViewById(R.id.rl_about_us);
        rl_about_us.setOnClickListener(this);

//        tb_p2p = (ToggleButton) findViewById(R.id.tb_p2p);
//        tb_p2p.setOnCheckedChangeListener(this);
//        ib_p2p = (ImageButton) findViewById(R.id.ib_p2p);
//        
//        tb_screenoff = (ToggleButton) findViewById(R.id.tb_screenoff);
//        tb_screenoff.setOnCheckedChangeListener(this);
//        ib_screenoff = (ImageButton) findViewById(R.id.ib_screenoff);
        
        
        // 如果消息振动提示是关闭状态，则禁用 rl_changeOfflinePin
        if (TerminalConfigMgr.getNotificationVibrate(this)) {
            // 脱机PIN
            tb_offlinePin.setChecked(true);
//            rl_changeOfflinePin.setVisibility(View.VISIBLE);
//            bFirstChangeFlag = false;
        } else {
            // 联机PIN
            tb_offlinePin.setChecked(false);
//            rl_changeOfflinePin.setVisibility(View.GONE);
//            bFirstChangeFlag = false;
        }
//        if (TerminalConfigMgr.getShowOfflineContacts(this)) {
//        	tb_p2p.setChecked(true);
//        }else{
//        	tb_p2p.setChecked(false);
//        }
//        if (TerminalConfigMgr.getUseAutoAway(this)) {
//        	tb_screenoff.setChecked(true);
//        }else{
//        	tb_screenoff.setChecked(false);
//        }
//        
//        et_screenoff_show_setting = (EditText) findViewById(R.id.et_screenoff_show_setting);
//        et_screenoff_show_setting.clearFocus();
//        et_screenoff_show_setting.setText(String.valueOf(TerminalConfigMgr.getAutoAwayMsg(this)));
        
//        et_serveraddr = (EditText) findViewById(R.id.et_serveraddr);
//        et_serveraddr.clearFocus();
//        et_serveraddr.setText(String.valueOf(TerminalConfigMgr.getServerAddr(this)));
//        
//        et_serverport = (EditText) findViewById(R.id.et_serverport);
//        et_serverport.clearFocus();
//        et_serverport.setText(String.valueOf(TerminalConfigMgr.getServerPort(this)));
        
        mCancelBt = (Button) findViewById(R.id.loginanim_cancel_button);//安全退出
        mCancelBt.setOnClickListener(this);
		
	    mImageFetcher = new ImageFetcher(this, 240);
	    mImageFetcher.setUListype(0);
	    mImageFetcher.setLoadingImage(R.drawable.empty_photo);
	    mImageFetcher.setExitTasksEarly(false);
//	    this.registerReceiver(mReceiver, new IntentFilter(BeemBroadcastReceiver.BEEM_CONNECTION_CLOSED));//原来的网络状态注释掉
	    
        //网络状态start
        mNetErrorView = findViewById(R.id.net_status_bar_top);
        mConnect_status_info = (TextView)mNetErrorView.findViewById(R.id.net_status_bar_info_top2);
        mConnect_status_btn = (ImageView)mNetErrorView.findViewById(R.id.net_status_bar_btn);
        mConnect_status_btn.setOnClickListener(this);
        
	    IntentFilter mFilter = new IntentFilter();
	    mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); // 添加接收网络连接状态改变的Action
	    registerReceiver(mNetWorkReceiver, mFilter);
        /* 添加自己实现的PhoneStateListener */
        myPhoneCallListener = new exPhoneCallListener();
       
       /* 取得电话服务 */
        tm =(TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
       
        /* 注册电话通信Listener */
        tm.listen(myPhoneCallListener,PhoneStateListener.LISTEN_CALL_STATE);
	    //网络状态end
	    
	    duitangInfoAdapter = DuitangInfoAdapter.getInstance(this);
	    tContactGroupAdapter = TContactGroupAdapter.getInstance(this);
	    sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
	    
	    
	    //从本地数据库中先加载展示start
	    preLoad();
		mHandler.sendEmptyMessage(8);
		//从本地数据库中先加载展示end
		
	    SpiceApplication.getInstance().addActivity(this);
    }
    private Intent intent;
//    private BaseDialog mBaseDialog;
	public void onClick(View v) {
		switch (v.getId()) {
		//网络设置
        case R.id.net_status_bar_btn:
			setNetworkMethod(this);
		break;
		case R.id.rl_verify_version://检测新版本
//			yesOrNoUpdataApk();
			break;
		case R.id.rl_about_us://关于我们
//			intent = new Intent(this, AboutUsActivity.class);//AdvancedSearch ProfileActivity
////        	intent = new Intent(this, AddDynamicsActivity.class);
//        	intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            startActivity(intent);
//		    finish();
			break;
		case R.id.rl_change_offline_pin:
			if(ObjectCache.getStatus("isConnected", getApplicationContext())
					&& BeemConnectivity.isConnected(getApplicationContext())){
//	        	intent = new Intent(this, ModifyPasswordActivity.class);//AdvancedSearch ProfileActivity
////	        	intent = new Intent(this, AddDynamicsActivity.class);
//	        	intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//	            startActivity(intent);
//			    finish();
			}
			break;
		case R.id.more_profile:
//			if(this.JIDWithRes!=null){
			if(ObjectCache.getStatus("isConnected", getApplicationContext())
					&& BeemConnectivity.isConnected(getApplicationContext())){
				try {
			    	if(mXmppFacade!=null){
				    	if (mXmppFacade.getXmppConnectionAdapter()!=null 
								&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null
								&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected() 
				    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
				    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAlive()
//								&& mXmppFacade.getXmppConnectionAdapter().login()//注意，第三方登陆login之前，需要调用框架本身的auth接口
								&& mXmppFacade.getXmppConnectionAdapter().getJID()!=null
								&& mXmppFacade.getXmppConnectionAdapter().getJID().length()!=0
								&& !mXmppFacade.getXmppConnectionAdapter().getJID().equalsIgnoreCase("null")
				    			){
	        	intent = new Intent(this, OtherProfileActivity.class);//ManagermentActivity.class
	        	SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
	    	    String login = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
	        	intent.putExtra("searchkey", login);
//	        	intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	            startActivity(intent);
	            finish();
				    	}
			    	}
				}catch(Exception e){
					
				}
			}
//			}
			break;			
		case R.id.more_profile2:
////			if(this.JIDWithRes!=null){
//			if(ObjectCache.getStatus("isConnected", getApplicationContext())
//					&& BeemConnectivity.isConnected(getApplicationContext())){
//	        	intent = new Intent(this, OtherProfileActivity.class);
//	        	intent.putExtra("JIDWithRes", this.JIDWithRes);
//	        	intent.putExtra("roomname", "");
//	        	intent.putExtra("nickname", nickname);
//	        	intent.putExtra("name", nickname);
////	        	intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//	            startActivity(intent);
//	            finish();
//			}
////			}
			break;
		case R.id.loginanim_cancel_button:
			mBaseDialog = BaseDialog.getDialog(PreferenceActivity.this, "安全退出", "您确定要退出应用吗?",
					"确定", new DialogInterface.OnClickListener() {
		
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							
							XmppConnectionAdapter.isPause = true;
							XmppConnectionAdapter.isReconnectFlag = false;
							if(XmppConnectionAdapter.instance!=null)
								XmppConnectionAdapter.instance.resetApplication();
							XmppConnectionAdapter.instance = null;
							stopService(SERVICE_INTENT);
//							finishNew();
							finish();
							
							SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(PreferenceActivity.this);
							String login = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
							(new DeviceUuidFactory2(mContext,login)).remove(mContext);//用户手动退出登录时，删除uuid记录，防止统一部手机上，使用不同账号登录时uuid重复问题
							SpiceApplication.getInstance().exit();
							BeemApplication.getInstance().exit();
					        // 杀死该应用进程
					        android.os.Process.killProcess(android.os.Process.myPid());
					        System.exit(0);
						}
			},"取消", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();;
				}
			});
			mBaseDialog.show();
			
			break;
		default:
			break;
		}
	}
	Handler mHandler = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
//				if(errorType==5){
					
					Iterator iter = linkedList.entrySet().iterator();
					Map.Entry entry = null;
					Object key = null;
					Object val = null;
					ContactGroup detail = null;
					while (iter.hasNext()) {
		    			entry = (Map.Entry) iter.next();
		    			key = entry.getKey();
		    			val = entry.getValue();
		    			detail = (ContactGroup)val;
					}
					if(detail!=null){
//						showCustomToast(detail.getAvatarPath()!=null?detail.getAvatarPath():"photo");//
						imgurl = detail.getAvatarPath();
						sex = detail.getSex()+"";
						age =detail.getBirthyear()+"-"+detail.getBirthmonth()+"-"+detail.getBirthday();
						sign = detail.getNote();
						
						//查询成功则以最新数据更新本地数据库
						contactGroup = new ContactGroup(sharedPrefs.getString("uidStr", "")+"@0"+"/"+sharedPrefs.getString(BeemApplication.ACCOUNT_USERNAME_KEY, ""));//登录成功用户个人信息存储到本地sqlite
                    	contactGroup.setName(detail.getName());
                    	contactGroup.setAvatar(detail.getAvatar());
                    	contactGroup.setAvatarPath(detail.getAvatarPath());
                    	contactGroup.setSex(detail.getSex());
                    	contactGroup.setNote(detail.getNote());
                    	contactGroup.setEmail(detail.getEmail());
                    	contactGroup.setBirthyear(detail.getBirthyear());
                    	contactGroup.setBirthmonth(detail.getBirthmonth());
                    	contactGroup.setBirthday(detail.getBirthday());
                    	contactGroup.setType(0);
                    	tContactGroupAdapter.addTContactGroup(contactGroup,StringUtils.parseBareAddress(sharedPrefs.getString("uidStr", "")+"@0"));
					}
					
				if(mIvUserPhoto != null && imgurl!=null)
//					mImageFetcher.loadRoundImage(XmppConnectionAdapter.downloadPrefix.replace("/javacenterhome/","/")+imgurl, mIvUserPhoto,null);
				mImageFetcher.loadRoundImage(XmppConnectionAdapter.downloadPrefix+imgurl, mIvUserPhoto,null);
//				showCustomToast(XmppConnectionAdapter.downloadPrefix+imgurl);//
		        if(nickNameTextView != null && nickname !=null)
		        	nickNameTextView.setText(nickname);
//		        if(ageTextView != null && age !=null)
//		        	ageTextView.setText(age);
	            if(user_item_iv_gender!=null && sex!=null
	            		&& !sex.equalsIgnoreCase("null")
	            		&& sex.length()!=0){
	            	if(sex.equals("1")){//1男，2女
	            		user_item_layout_gender.setBackgroundResource(R.drawable.bg_gender_male);
	            		user_item_iv_gender.setImageResource(R.drawable.ic_user_male);
	            	}else{
	            		user_item_layout_gender.setBackgroundResource(R.drawable.bg_gender_famal);
	            		user_item_iv_gender.setImageResource(R.drawable.ic_user_famale);
	            	}
	            }
	            int age1 = 0;
	            if(ageTextView != null && detail!=null ){//&& age !=null
            		//&& !age.equalsIgnoreCase("null")
            		//&& age.length()!=0
//	            	String[] yyyymmdd = age.split("-");
//	            	try{
//	            		age1 = TextUtils.getAge(Integer.parseInt(yyyymmdd[0]),
//	            				Integer.parseInt(yyyymmdd[1]),
//	            				Integer.parseInt(yyyymmdd[2]));
//	            	}catch(Exception e){
//	            		age1 = 0;
//	            	}
//	            	if(age1>200)
//	            		ageTextView.setText("未知");
//	                else
//	                	ageTextView.setText(age+"");
	            	int age2 = 0;
	                if(detail.getBirthyear()!=null
	                		&& !detail.getBirthyear().equalsIgnoreCase("null")
	                		&& detail.getBirthyear().length()!=0
	                		&& detail.getBirthmonth()!=null
	                		&& !detail.getBirthmonth().equalsIgnoreCase("null")
	                		&& detail.getBirthmonth().length()!=0
	                		&& detail.getBirthday()!=null
	                		&& !detail.getBirthday().equalsIgnoreCase("null")
	                		&& detail.getBirthday().length()!=0){
	                	
	                	try{
	                		age2 = TextUtils.getAge(Integer.parseInt(detail.getBirthyear()),
	                				Integer.parseInt(detail.getBirthmonth()),
	                				Integer.parseInt(detail.getBirthday()));
	                	}catch(Exception e){
	                		e.printStackTrace();
	                		age2 = 0;
	                	}
	                }
	                if(age2>200)
	                	ageTextView.setText("未知");
	                else
	                	ageTextView.setText(age2+"");
	            }
		        if(accountTextView != null && account !=null)
		        	accountTextView.setText(account);
		        if(signTextView != null && sign !=null)
		        	signTextView.setText(sign);
		        if(errorType==5){
				}else{
//					Toast.makeText(GpsSearchResPullRefListActivity.this,errorMsg[errorType], 1000).show();
					bulid();
					showCustomToast(errorMsg[errorType]);
				}
				break;
			case 1:
				
				progress.setText(msg.arg1+"%");//20150831 第三种方法
				bar.setProgress(msg.arg1);//20150831 第三种方法
				break;
			case 2:
				progress.setText("100%");//20150831 第三种方法
				bar.setProgress(100);//20150831 第三种方法
				
				creatingProgress.dismiss();
//				transformfilepath = 
//				if(transformfilepath.lastIndexOf("/")!=-1)
//					transformfilepath = XmppConnectionAdapter.downloadPrefix+"9999"+"/"+transformfilepath.substring(transformfilepath.lastIndexOf("/")+1);
//				else
//					transformfilepath = XmppConnectionAdapter.downloadPrefix+"9999"+"/"+transformfilepath;
				if(mIvUserPhoto != null)
					mImageFetcher.loadRoundImage(transformfilepath, mIvUserPhoto,null);
				break;
			case 3:
				progress.setText("上传失败!");
				creatingProgress.dismiss();
				break;
			case 4:
				initialProgressDialog();
				creatingProgress.show();
				break;
			case 8:
				bulid();
				break;
			default:
				if(errorType!=5)
					showCustomToast(errorMsg[errorType]);
				break;
			}
		}

	};
	private void getProfile() {

			putAsyncTask(new com.beem.push.utils.AsyncTask<Void, Void, Boolean>() {

				@Override
				protected void onPreExecute() {
					super.onPreExecute();
				    /**加载前先显示缓存数据start*/
					Log.e("MMMMMMMMMMMM####20140810登录状态####MMMMMMMMMMMM", "++++++++++++++登录状态="+ObjectCache.getStatus("isConnected", getApplicationContext())+"++++++++++++");
				    if(ObjectCache.getStatus("isConnected", getApplicationContext())){
//						errorType = 5;
						preLoad();
						mHandler.sendEmptyMessage(8);
//						bulid();
				    }
				    /**加载前先显示缓存数据end*/
					showLoadingDialog("正在加载,请稍后...");
				}

				@Override
				protected Boolean doInBackground(Void... params) {
					initProfile();
					return true;
				}

				@Override
				protected void onPostExecute(Boolean result) {
					super.onPostExecute(result);
					dismissLoadingDialog();
					if (!result) {
						showCustomToast("数据加载失败...");
					} else {
						mHandler.sendEmptyMessage(0);
					}
				}

			});
	}
    public void initProfile(){
    	if(ObjectCache.getStatus("isConnected", getApplicationContext())){//已登录
	    	if(BeemConnectivity.isConnected(getApplicationContext())){
			    try{
			    	if(mXmppFacade!=null){
					    if(mXmppFacade.getXmppConnectionAdapter()!=null 
								&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null//&& !mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
								&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected()
								&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
								&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAlive()){
					    	
					    	nickname = mXmppFacade.getXmppConnectionAdapter().getName();
					    	account = StringUtils.parseBareAddress(mXmppFacade.getXmppConnectionAdapter().getJID());
				    		SearchIQ reqXML = new SearchIQ();
				            reqXML.setId("1234567890");
				            reqXML.setApikey("abcdefghijklmnopqrstuvwxyz");
				            //当不是登录流程进入，比如是注册流程进入该页面时uid及searchkey字段有空bug存在
				            reqXML.setUid(StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID()));//2
				            reqXML.setSearchkey(mXmppFacade.getXmppConnectionAdapter().getName());//searchkey
				            
				            SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
				            String login = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
				            String uuid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().getUUID(this,login);
				            reqXML.setUuid(uuid);
//				            String hashcode = "";//apikey+view+orderby+uuid 使用登录成功后返回的sessionid作为密码做3des运算
				            String hash_dest_src = "abcdefghijklmnopqrstuvwxyz"+ StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID())+uuid;
				            String hash_dest = EncryptionUtil.getHash2(hash_dest_src, "SHA");
				            reqXML.setHashcode(hash_dest);
				            reqXML.setType(IQ.Type.SET);
				            String elementName = "searchiq"; 
				    		String namespace = "com:isharemessage:searchiq";
				    		SearchIQResponseProvider provider = new SearchIQResponseProvider();
				            Packet rt =  mXmppFacade.getXmppConnectionAdapter().excute(reqXML, "searchiq", "com:isharemessage:searchiq", provider);
				            
				            if(rt!=null){
				                if (rt instanceof SearchIQResponse) {
				                	final SearchIQResponse searchIQResponse = (SearchIQResponse) rt;

				                    if (searchIQResponse.getChildElementXML().contains(
				                            "com:isharemessage:searchiq")) {
//				    					PreferenceActivity.this.runOnUiThread(new Runnable() {
//					                    	
//	            							@Override
//	            							public void run() {
//	            								showCustomToast("服务器应答消息："+searchIQResponse.toXML().toString());
//	            							}
//	            						});
				                        String Id = searchIQResponse.getId();
				                        String Apikey = searchIQResponse.getApikey();
				                        HashMap cGroups = searchIQResponse.getCGroups();
				                        if(cGroups.size()!=0){
//					                        linkedList = new LinkedList(cGroups);
				                        	linkedList = cGroups;
//				                        	for(int q=0;q<cGroups.size();q++){
//				                        		linkedList.add(cGroups.get(q));
//				                        	}
					                        Log.e("响应packet结果解析...............", "Id="+Id+";Apikey="+Apikey); 
		//			                        mListContact = new ArrayList<Contact>(); 
		//			                        for(int k=0;k<cGroups.size();k++){
		//			                        	Log.e("响应packet结果解析...............", "cGroups"); 
		////			                        	mListContact.add(contact);
		//			                        }
					                        cGroups = null;
//					                        return true;
				                        }
				                    }
				                } 
				            }
				    		
				    		
				    		Log.e("================2015 TestActivity.java ================", "++++++++++++++initContactList()444++++++++++++++");

				    	    if(linkedList!=null && linkedList.size()!=0)
				    	    	errorType = 5;
				    	    else{
				    	    	if(linkedList!=null && linkedList.size()==0)
				    	    		errorType = 0;
				    	    	else
				    	    		errorType = 6;
				    	    }
							mBinded = true;//20130804 added by allen
			
					    }else
				    		errorType = 1;//客户端网络是ok的，但是服务器可能宕机了
			    	}else
			    		errorType = 2;
		        } catch (RemoteException e) {
		        	errorType = 3;
			    	e.printStackTrace();
			    } catch (Exception e){
			    	errorType = 3;
			    	e.printStackTrace();
			    }
	    	}else{
		    	errorType = 4;
		    }
    	}else{
    		if(BeemConnectivity.isConnected(getApplicationContext()))
    			errorType = 6;
    		else
    			errorType = 4;
    	}
    }
    String CurrentUid = "";
    /**
     * connection to service.
     * @author nikita
     */
    private class BeemServiceConnection implements ServiceConnection {

		/**
		 * constructor.
		 */
		public BeemServiceConnection() {
		}
	
		/**
		 * {@inheritDoc}
		 */
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
		    mXmppFacade = IXmppFacade.Stub.asInterface(service);
		    if(mXmppFacade!=null){
		    	mBinded = true;//20130804 added by allen
		    	try{
		    		mXmppFacade.getXmppConnectionAdapter().registerConnectionStatusCallback(PreferenceActivity.this);//网络状态相关
		    	CurrentUid = StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID());
		    	}catch(Exception e){}
		    getProfile();
		    }
		}
	
		/**
		 * {@inheritDoc}
		 */
		@Override
		public void onServiceDisconnected(ComponentName name) {
			 try{//网络状态相关
				    if(mXmppFacade!=null && mXmppFacade.getXmppConnectionAdapter()!=null)
				    	mXmppFacade.getXmppConnectionAdapter().unRegisterConnectionStatusCallback();
			    }catch (RemoteException e) {
			    	e.printStackTrace();
			    }
		    mXmppFacade = null;
		    mBinded = false;//20130804 added by allen
		    
		}
    }
    private static ExecutorService LIMITED_TASK_EXECUTOR;  
    static {  
        LIMITED_TASK_EXECUTOR = (ExecutorService) Executors.newFixedThreadPool(7);    
    }; 
    public List<com.beem.push.utils.AsyncTask<Void, Void, Boolean>> mAsyncTasks = new ArrayList<com.beem.push.utils.AsyncTask<Void, Void, Boolean>>();
    public void putAsyncTask(com.beem.push.utils.AsyncTask<Void, Void, Boolean> asyncTask) {
		mAsyncTasks.add(asyncTask.executeOnExecutor(LIMITED_TASK_EXECUTOR, null));
//		mAsyncTasks.add(asyncTask.execute());
	}

    public void clearAsyncTask() {
		Iterator<com.beem.push.utils.AsyncTask<Void, Void, Boolean>> iterator = mAsyncTasks
				.iterator();
		while (iterator.hasNext()) {
			com.beem.push.utils.AsyncTask<Void, Void, Boolean> asyncTask = iterator.next();
			if (asyncTask != null && !asyncTask.isCancelled()) {
				asyncTask.cancel(true);
			}
		}
		mAsyncTasks.clear();
	}
	

	protected void showLoadingDialog(String text) {
		if (text != null) {
			mLoadingDialog.setText(text);
		}
		mLoadingDialog.show();
	}

	protected void dismissLoadingDialog() {
		if (mLoadingDialog.isShowing()) {
			mLoadingDialog.dismiss();
		}
	}

	/** 显示自定义Toast提示(来自String) **/
	protected void showCustomToast(String text) {
		View toastRoot = LayoutInflater.from(PreferenceActivity.this).inflate(
				R.layout.common_toast, null);
		((HandyTextView) toastRoot.findViewById(R.id.toast_text)).setText(text);
		Toast toast = new Toast(PreferenceActivity.this);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.setDuration(Toast.LENGTH_SHORT);
		toast.setView(toastRoot);
		toast.show();
	}
    /**
     * {@inheritDoc}
     */
    @Override
    protected void onResume() {
		super.onResume();
		mImageFetcher.setExitTasksEarly(false);
		if (!mBinded){
			Intent intent = new Intent(this, BeemService.class);
//			intent.putExtra("uFlag_startfromsetting", "1");
			mBinded = bindService(intent, mServConn, BIND_AUTO_CREATE);
		}
    }
    @Override
    protected void onPause() {
		super.onPause();
		mImageFetcher.setExitTasksEarly(true);
//		if (mBinded) {
//			unbindService(mServConn);
//			mBinded = false;
//		}
    }

    /* (non-Javadoc)
     * @see android.app.Activity#onDestroy()
     */
    @Override
    protected void onDestroy() {
		super.onDestroy();
		mImageFetcher.onCancel_RoundImage();
	    try{//网络状态相关
		    if(mXmppFacade!=null && mXmppFacade.getXmppConnectionAdapter()!=null)
		    	mXmppFacade.getXmppConnectionAdapter().unRegisterConnectionStatusCallback();
	    }catch (RemoteException e) {
	    	e.printStackTrace();
	    }
		if (mBinded) {
			unbindService(mServConn);
			mBinded = false;
		}
//		this.unregisterReceiver(mReceiver);
		if(mBaseDialog2!=null && mBaseDialog2.isShowing())
			mBaseDialog2.cancel();
		if(mBaseDialog!=null && mBaseDialog.isShowing())
			mBaseDialog.cancel();
		clearAsyncTask();
		//网络状态start
		unregisterReceiver(mNetWorkReceiver); // 删除广播
		if(tm!=null){
			tm.listen(myPhoneCallListener,PhoneStateListener.LISTEN_NONE);//取消监听即可
			tm = null;
		}
		if(myPhoneCallListener!=null)
			myPhoneCallListener = null;
		//网络状态end
//		SpiceApplication.getInstance().exit();
//        // 保存配置信息
//        try {
////            EditText et_screenoff_show_setting;//屏幕关闭状态签名
////            EditText et_serveraddr;//服务器地址
////            EditText et_serverport;//服务器端口
////            threshold = Integer.valueOf(et_upload.getText().toString());
//            TerminalConfigMgr.setAutoAwayMsg(this, et_screenoff_show_setting.getText().toString());
////            TerminalConfigMgr.setServerAddr(this, et_serveraddr.getText().toString());
////            TerminalConfigMgr.setServerPort(this, et_serverport.getText().toString());
//        } catch (Exception e) {
//            // TODO: handle exception
//        }
    }
    
    private RelativeLayout.LayoutParams params;
    private TranslateAnimation animation;
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//        if (buttonView.getId() == R.id.tb_p2p) {//不显示离线用户
//            params = (RelativeLayout.LayoutParams) ib_p2p
//                    .getLayoutParams();
//            if (isChecked) {
//                // 调整位置
//                // off -> on
//                params.addRule(RelativeLayout.ALIGN_RIGHT, -1);
//                params.addRule(RelativeLayout.ALIGN_LEFT, R.id.tb_p2p);
//
//                ib_p2p.setLayoutParams(params);
//                ib_p2p.setImageResource(R.drawable.progress_thumb_selector);
//                tb_p2p.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL);
//                // 播放动画
//                animation = new TranslateAnimation(dip2px(
//                        this, 40), 0, 0, 0);
//                animation.setDuration(200);
//                ib_p2p.startAnimation(animation);
////                TerminalConfigMgr.isWifiP2P = true;
////                TerminalConfigMgr.setP2PFlag(this, TerminalConfigMgr.isWifiP2P);
//                TerminalConfigMgr.setShowOfflineContacts(this,true);
//
//            } else {
//                // 调整位置
//                // on -> off
//                params.addRule(RelativeLayout.ALIGN_RIGHT, R.id.tb_p2p);
//                params.addRule(RelativeLayout.ALIGN_LEFT, -1);
//                ib_p2p.setLayoutParams(params);
//                ib_p2p.setImageResource(R.drawable.progress_thumb_off_selector);
//                tb_p2p.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
//                // 播放动画
//                animation = new TranslateAnimation(dip2px(
//                        this, -40), 0, 0, 0);
//                animation.setDuration(200);
//                ib_p2p.startAnimation(animation);
//
////                TerminalConfigMgr.isWifiP2P = false;
////                TerminalConfigMgr.setP2PFlag(this, TerminalConfigMgr.isWifiP2P);
//                TerminalConfigMgr.setShowOfflineContacts(this,false);
//            }
//        } else 
        	
        	if (buttonView.getId() == R.id.tb_offlinePin) {//消息振动提示

            params = (RelativeLayout.LayoutParams) ib_offlinePin
                    .getLayoutParams();
            if (isChecked) {
                // 调整位置
                // off -> on
                params.addRule(RelativeLayout.ALIGN_RIGHT, -1);
                params.addRule(RelativeLayout.ALIGN_LEFT, R.id.tb_offlinePin);

                ib_offlinePin.setLayoutParams(params);
                ib_offlinePin
                        .setImageResource(R.drawable.progress_thumb_selector);
                tb_offlinePin.setGravity(Gravity.RIGHT
                        | Gravity.CENTER_VERTICAL);
                // 播放动画
                animation = new TranslateAnimation(dip2px(
                        this, 40), 0, 0, 0);
                animation.setDuration(200);
                ib_offlinePin.startAnimation(animation);

//                rl_changeOfflinePin.setVisibility(View.VISIBLE);

//                if (bFirstChangeFlag == false) {
////                    Bundle bundle = new Bundle();
////                    Intent intent;
////
////                    intent = new Intent(this, LoginActivity.class);
////                    bundle.putString("Function", "setActivity");
////
////                    intent.putExtras(bundle);
////                    startActivityWithAnim(intent);
////                    finish();
//                }
                TerminalConfigMgr.setNotificationVibrate(this, true);
            } else {
                // 调整位置
                // on -> off
                params.addRule(RelativeLayout.ALIGN_RIGHT, R.id.tb_offlinePin);
                params.addRule(RelativeLayout.ALIGN_LEFT, -1);
                ib_offlinePin.setLayoutParams(params);
                ib_offlinePin
                        .setImageResource(R.drawable.progress_thumb_off_selector);
                tb_offlinePin
                        .setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
                // 播放动画
                animation = new TranslateAnimation(dip2px(
                        this, -40), 0, 0, 0);
                animation.setDuration(200);
                ib_offlinePin.startAnimation(animation);

//                rl_changeOfflinePin.setVisibility(View.GONE);
//                TerminalConfigMgr.setOnlineLoginVerfyFlag(this, "1");
                TerminalConfigMgr.setNotificationVibrate(this, false);
            }
        }
//        else if (buttonView.getId() == R.id.tb_screenoff) {//屏幕关闭修改状态
//
//            params = (RelativeLayout.LayoutParams) ib_screenoff
//                    .getLayoutParams();
//            if (isChecked) {
//                // 调整位置
//                // off -> on
//                params.addRule(RelativeLayout.ALIGN_RIGHT, -1);
//                params.addRule(RelativeLayout.ALIGN_LEFT, R.id.tb_screenoff);
//
//                ib_screenoff.setLayoutParams(params);
//                ib_screenoff
//                        .setImageResource(R.drawable.progress_thumb_selector);
//                tb_screenoff.setGravity(Gravity.RIGHT
//                        | Gravity.CENTER_VERTICAL);
//                // 播放动画
//                animation = new TranslateAnimation(dip2px(
//                        this, 40), 0, 0, 0);
//                animation.setDuration(200);
//                ib_screenoff.startAnimation(animation);
//                TerminalConfigMgr.setUseAutoAway(this,true);
//
////                rl_changeOfflinePin.setVisibility(View.VISIBLE);
//
////                if (bFirstChangeFlag == false) {
//////                    Bundle bundle = new Bundle();
//////                    Intent intent;
//////
//////                    intent = new Intent(this, LoginActivity.class);
//////                    bundle.putString("Function", "setActivity");
//////
//////                    intent.putExtras(bundle);
//////                    startActivityWithAnim(intent);
//////                    finish();
////                }
//            } else {
//                // 调整位置
//                // on -> off
//                params.addRule(RelativeLayout.ALIGN_RIGHT, R.id.tb_screenoff);
//                params.addRule(RelativeLayout.ALIGN_LEFT, -1);
//                ib_screenoff.setLayoutParams(params);
//                ib_screenoff
//                        .setImageResource(R.drawable.progress_thumb_off_selector);
//                tb_screenoff
//                        .setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
//                // 播放动画
//                animation = new TranslateAnimation(dip2px(
//                        this, -40), 0, 0, 0);
//                animation.setDuration(200);
//                ib_screenoff.startAnimation(animation);
//                TerminalConfigMgr.setUseAutoAway(this,false);
//
////                rl_changeOfflinePin.setVisibility(View.GONE);
////                TerminalConfigMgr.setOnlineLoginVerfyFlag(this, "1");
//            }
//        }
    }
    
    public int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
	private class OnRightImageButtonClickListener implements
	onRightImageButtonClickListener {
	
		@Override
		public void onClick() {
			startActivity(new Intent(PreferenceActivity.this, Login.class));
			PreferenceActivity.this.finish();
		}
	}
	
	private String[] errorMsg = new String[]{"抱歉,没有找到相关结果.",
			"服务连接中1-1,请稍候再试.",
			"服务连接中1-2,请稍候再试.",
			"服务连接中1-3,请稍候再试.",
			"网络连接不可用,请检查你的网络设置.",
			"已登录",
			"未登录",
			"请求异常,稍候重试!"};
	private int errorType = 5;
	
	private SharedPreferences sharedPrefs = null;
	private TContactGroupAdapter tContactGroupAdapter = null;
	private TContactGroup tg = null;
	private ContactGroup contactGroup = null;
	public void preLoad(){//联网前先显示缓存/本地数据库内容
//		Object obj2 = ObjectCache.get("mContact_"+mLogin+"_Preference",this);
//		Log.e("MMMMMMMMMMMM####20140810缓存不为空####MMMMMMMMMMMM", "++++++++++++++缓存不为空="+(obj2!=null));
//		if(obj2!=null){
//			contact = (Contact)obj2;
//        	nickname = contact.getName();
//        	sex = contact.getGender();
//        	age = contact.getBirthday();
//        	account = StringUtils.parseName(contact.getJIDWithRes());
//        	JIDWithRes = contact.getJIDWithRes();
//        	sign = contact.getSign();
//        	
//            if(contact.getAvatarId()!=null 
//            		&& contact.getAvatarId().length()!=0 
//            		&& !contact.getAvatarId().equalsIgnoreCase("null")
//            		&& (
//            				contact.getAvatarId().toLowerCase().endsWith(".jpg")
//            				|| contact.getAvatarId().toLowerCase().endsWith(".png")
//            				|| contact.getAvatarId().toLowerCase().endsWith(".bmp")
//            				|| contact.getAvatarId().toLowerCase().endsWith(".gif")
//            			))
//            	imgurl = XmppConnectionAdapter.downloadPrefix+StringUtils.parseName(contact.getJIDWithRes())+"/"+contact.getAvatarId();//+"thumbnail_"
//		}
//		
//		tContactGroupAdapter = TContactGroupAdapter.getInstance(this);
//		if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mMsgText.getBareJid()))!=null){
//			
//		}
		
//		tg = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(sharedPrefs.getString("uidStr", "")+"@0"));
		String tmp2 = sharedPrefs.getString("uidStr"+sharedPrefs.getString(BeemApplication.ACCOUNT_USERNAME_KEY, ""), "");
		tg = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(tmp2+"@0"));
		if(tg!=null){
			imgurl = tg.getAvatarPath();
			if(tg.getName()!=null && tg.getName().length()!=0)
				nickname = tg.getName();
			else
				nickname = tg.getUsername();
			sex = tg.getSex()+"";
			if(tg.getBirthyear()!=null && tg.getBirthyear().length()!=0)
			age = tg.getBirthyear()+tg.getBirthmonth()+tg.getBirthday();
			account = tg.getUsername();
			sign = tg.getNote();
		}
	}
	public void bulid(){
//		if(errorType==5){
			if(mIvUserPhoto != null && imgurl!=null)
				mImageFetcher.loadRoundImage(XmppConnectionAdapter.downloadPrefix+imgurl, mIvUserPhoto,null);
	        if(nickNameTextView != null && nickname !=null)
	        	nickNameTextView.setText(nickname);
//	        if(ageTextView != null && age !=null)
//	        	ageTextView.setText(age);
            if(user_item_iv_gender!=null && sex!=null
            		&& !sex.equalsIgnoreCase("null")
            		&& sex.length()!=0){
            	if(sex.equals("1")){//1男，2女
            		user_item_layout_gender.setBackgroundResource(R.drawable.bg_gender_male);
            		user_item_iv_gender.setImageResource(R.drawable.ic_user_male);
            	}else{
            		user_item_layout_gender.setBackgroundResource(R.drawable.bg_gender_famal);
            		user_item_iv_gender.setImageResource(R.drawable.ic_user_famale);
            	}
            }
            int age1 = 0;
            if(ageTextView != null && age !=null
            		&& !age.equalsIgnoreCase("null")
            		&& age.length()!=0){
            	String[] yyyymmdd = age.split("-");
            	try{
            		age1 = TextUtils.getAge(Integer.parseInt(yyyymmdd[0]),
            				Integer.parseInt(yyyymmdd[1]),
            				Integer.parseInt(yyyymmdd[2]));
            	}catch(Exception e){
            		age1 = 0;
            	}
            	ageTextView.setText(age1+"");
            }
	        if(accountTextView != null && account !=null)
	        	accountTextView.setText(account);
	        if(signTextView != null && sign !=null)
	        	signTextView.setText(sign);
//			}else{
////				Toast.makeText(GpsSearchResPullRefListActivity.this,errorMsg[errorType], 1000).show();
//				showCustomToast(errorMsg[errorType]);
//			}
	}
	

	private BaseDialog mBaseDialog2;
	private BaseDialog mBaseDialog;
	
//	private String packageName;
//	private String nowVersion = "";
//	private String newVersion = "";
////	private ProgressDialog pBar;
//	/**
//	 * Role:是否更新版本<BR>
//	 * Date:2012-4-5<BR>
//	 * 
//	 * @author ZHENSHI)peijiangping
//	 */
//	private void yesOrNoUpdataApk() {
////		packageName = this.getPackageName();
////		String nowVersion = getVerCode(AccConfActivity.this);
////		String newVersion = goToCheckNewVersion();
////		if (newVersion.equals("Error")) {
////			return 0;
////		}
////		if (Double.valueOf(newVersion) > Double.valueOf(nowVersion)) {
////			doNewVersionUpdate(nowVersion, newVersion);
////		}
////		return 1;
//		packageName = this.getPackageName();
//		putAsyncTask(new com.beem.push.utils.AsyncTask<Void, Void, Boolean>() {
//			@Override
//			protected void onPreExecute() {
//				super.onPreExecute();
//				showLoadingDialog("正在检测,请稍候...");
//			}
//
//			@Override
//			protected Boolean doInBackground(Void... params) {
//				
//				nowVersion = getVerCode(PreferenceActivity.this);
//				newVersion = goToCheckNewVersion(nowVersion);
//				return true;
//			}
//
//			@Override
//			protected void onPostExecute(Boolean result) {
//				super.onPostExecute(result);
//				dismissLoadingDialog();
//				if (!result) {
////					showCustomToast("删除失败...");
//					showCustomToast("版本检测失败...");
//				}else{
////					showCustomToast("删除成功...");
//					try{
//						if (newVersion.equals("Error"))
//							showCustomToast("版本检测失败...");
//						else if (Double.valueOf(newVersion) > Double.valueOf(nowVersion)) {
//							
//							mHandler.sendEmptyMessage(1);
//						}else
//							showCustomToast("当前已是最新版本.");
//					}catch(Exception e){
//						showCustomToast("版本检测失败...");
//					}
//				}
////				mHandler.sendEmptyMessage(0);
//				
//			}
//
//		});
//	}
//	/**
//	 * Role:是否进行更新提示框<BR>
//	 * Date:2012-4-5<BR>
//	 * 
//	 * @author ZHENSHI)peijiangping
//	 */
//	private BaseDialog mBaseDialog;
//	private void doNewVersionUpdate(String nowVersion, String newVersion,StringTokenizer st) {
//		StringBuffer sb = new StringBuffer();
//		sb.append("当前版本:");
//		sb.append(nowVersion);
//		sb.append("\n发现新版本:");
//		sb.append(newVersion);
//		sb.append("\n更新说明:\n");
////		sb.append(verdesc);
////		if(verdescArry!=null)
////		for(int i=0;i<verdescArry.length;i++){
////			sb.append(verdescArry[i]+"\n");
////		}
//		if(st!=null)
//		while(st.hasMoreTokens()){
////			System.out.println("20141223返回值解析verdescArry[j]=" + st.nextToken());
//			sb.append(st.nextToken()+"\n");
//		}
//		if(mustupdateornot.equals("0"))
//			sb.append("\n是否更新?");
//		else
//			sb.append("\n您必须下载更新才能正常使用!");
////		Dialog dialog = new AlertDialog.Builder(AccConfActivity.this)
////				.setTitle("软件更新")
////				.setMessage(sb.toString())
////				// 设置内容
////				.setPositiveButton("更新",// 设置确定按钮
////						new DialogInterface.OnClickListener() {
////							@Override
////							public void onClick(DialogInterface dialog,
////									int which) {
////								pBar = new ProgressDialog(
////										AccConfActivity.this);
////								pBar.setTitle("正在下载");
////								pBar.setMessage("请稍候...");
////								// pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
////								pBar.show();
////								goToDownloadApk();
////							}
////						})
////				.setNegativeButton("暂不更新",
////						new DialogInterface.OnClickListener() {
////							public void onClick(DialogInterface dialog,
////									int whichButton) {
////								// 点击"取消"按钮之后退出程序
//////								finish();
////								dialog.dismiss();
////							}
////						}).create();// 创建
////		// 显示对话框
////		dialog.show();
//		
//		mBaseDialog = BaseDialog.getDialog(PreferenceActivity.this, "软件更新", sb.toString(),
//				"更新", new DialogInterface.OnClickListener() {
//	
//					@Override
//					public void onClick(DialogInterface dialog, int which) {
//						dialog.dismiss();
////						pBar = new ProgressDialog(
////								AccConfActivity.this);
////						pBar.setTitle("正在下载");
////						pBar.setMessage("请稍候...");
////						// pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
////						pBar.show();
//						Beginning();
//						goToDownloadApk();
//					}
//				},(mustupdateornot.equals("0"))?"暂不更新":"取消并退出", new DialogInterface.OnClickListener() {
//	
//					@Override
//					public void onClick(DialogInterface dialog, int which) {
//						if(mustupdateornot.equals("0"))
//							dialog.dismiss();
//						else
//							finish();
//					}
//				});
//		mBaseDialog.show();
//	}
////	private ProgressBar pb;
////	private TextView tv;
//	public static int loading_process;
//	private BaseDialog mBaseDialog2;
//	public void Beginning(){
////		LinearLayout ll = (LinearLayout) LayoutInflater.from(AccConfActivity.this).inflate(
////				R.layout.loadapk, null);
////		pb = (ProgressBar) ll.findViewById(R.id.down_pb);
////		tv = (TextView) ll.findViewById(R.id.tv);
//		
//		mBaseDialog2 = BaseDialog.getDialog(PreferenceActivity.this, "版本更新进度提示", "加载进度",true,
//				"后台下载", new DialogInterface.OnClickListener() {
//	
//					@Override
//					public void onClick(DialogInterface dialog, int which) {
//						Intent intent=new Intent(PreferenceActivity.this, VersionService.class);  
//						startService(intent);
//						dialog.dismiss();
//					}
//				});
//		mBaseDialog2.show();
//		
//		
//	}
//	/**
//	 * Role:开启下载apk的线程<BR>
//	 * Date:2012-4-6<BR>
//	 * 
//	 * @author ZHENSHI)peijiangping
//	 */
//	private void goToDownloadApk() {
//		new Thread(new DownloadApkThread(handler,downloadPrefix+apkname,apkname)).start();
//	}
//	public Handler handler = new Handler() {
//		public void handleMessage(android.os.Message msg) {
//			if (!Thread.currentThread().isInterrupted()) {
//				switch (msg.what) {
//				case 1:
////					pb.setProgress(msg.arg1);
//					mBaseDialog2.getProgress().setProgress(msg.arg1);
//					loading_process = msg.arg1;
////					tv.setText("已为您加载了：" + loading_process + "%");
//					mBaseDialog2.getHtvMessage().setText("已为您加载了：" + loading_process + "%");
//					break;
//				case 2:
//					
//					Intent intent = new Intent(Intent.ACTION_VIEW);
//					intent.setDataAndType(Uri.fromFile(new File("/sdcard/update", apkname)),
//							"application/vnd.android.package-archive");
//					startActivity(intent);
//					mBaseDialog2.dismiss();
//					break;
//				case -1:
//					mBaseDialog2.dismiss();
//					String error = msg.getData().getString("error");
////					Toast.makeText(AccConfActivity.this, error, 1).show();
//					showCustomToast("下载失败！！"+error);
//					break;
//				}
//			}
//			super.handleMessage(msg);
//			
//		}
//	};
//	/**
//	 * Role:去获取当前的应用最新版本<BR>
//	 * Date:2012-4-5<BR>
//	 * 
//	 * @author ZHENSHI)peijiangping
//	 */
////    String[] verdescArry = null;
//    StringTokenizer st = null;
//	private String goToCheckNewVersion(String nowVersion) {
//		System.out.println("goToCheckNewVersion");
//		String result = null;
////		final String url = "http://192.168.1.41:8080/TestHttpServlet/GetVersionServlet";
////		final String url = "http://10.0.2.2:8080/apkvercheck/GetVersionServlet";
////		HttpConnect hc = new HttpConnect(url, this);
//		HttpConnect hc = new HttpConnect(apkvercheck,this);
//		List<NameValuePair> params = new ArrayList<NameValuePair>();  
//        params.add(new BasicNameValuePair("nowVersion", nowVersion));
////		result = hc.getDataAsString(null);
//        result = hc.getDataAsString(params);
//		
//		if (result.equals("Error")) {
//			return "Error";
//		}
//		try {
//			array = new JSONArray(result);
//			for (int i = 0; i < array.length(); i++) {
//				object = array.getJSONObject(i);
//				apkversion = object.getString("apkversion");
//				apkname = object.getString("apkname");
//				verdesc = object.getString("verdesc");
//				mustupdateornot = object.getString("mustupdateornot");
//				if(mustupdateornot==null 
//						|| mustupdateornot.equalsIgnoreCase("null")
//						|| mustupdateornot.length()==0)
//					mustupdateornot = "0";
////				verdescArry = (verdesc).split("//|");
////				verdesc = "";
////				for(int j=0;j<verdescArry.length;j++){
////					System.out.println("20141223返回值解析verdescArry["+j+"]=" + verdescArry[j]);
////				}
//				st = new StringTokenizer(verdesc , "|") ;
////				while(st.hasMoreTokens()){
////					System.out.println("20141223返回值解析verdescArry[j]=" + st.nextToken());
////				}
//				System.out.println("20141223返回值解析apkversion" + apkversion);
//				System.out.println("20141223返回值解析apkname" + apkname);
//				System.out.println("20141223返回值解析verdesc" + verdesc);
//				System.out.println("20141223返回值解析mustupdateornot" + mustupdateornot);
//			}
//		} catch (JSONException e) {
//			e.printStackTrace();
//		} catch(Exception e){
//			e.printStackTrace();
//		}
//		return apkversion;
//	}
//
//	/**
//	 * Role:取得程序的当前版本<BR>
//	 * Date:2012-4-5<BR>
//	 * 
//	 * @author ZHENSHI)peijiangping
//	 */
//	private String getVerCode(Context context) {
//		int verCode = 0;
//		String verName = null;
//		try {
//			verCode = context.getPackageManager()
//					.getPackageInfo(packageName, 0).versionCode;
//			verName = context.getPackageManager()
//					.getPackageInfo(packageName, 0).versionName;
//		} catch (NameNotFoundException e) {
//			System.out.println("no");
//		}
//		System.out.println("verCode" + verCode + "===" + "verName" + verName);
//		return verName;
//	}
	
    /**
     * Listener.
     */
    private class OkListener implements OnClickListener {
	
		/**
		 * Constructor.
		 */
		public OkListener() { }
	
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
				case R.id.reg_photo_layout_selectphoto:
					GalleryHelper.openGallerySingle(PreferenceActivity.this, true, new GalleryImageLoader());
					break;
	
				case R.id.reg_photo_layout_takepicture:
					takePhotoAction();
				break;
			}
	
		}
    };
    
	public void setUserPhoto(Bitmap bitmap) {
		if (bitmap != null) {
			mUserPhoto = bitmap;
			mIvUserPhoto.setImageBitmap(mUserPhoto);
			return;
		}
		showCustomToast("未获取到图片");
		mUserPhoto = null;
		mIvUserPhoto.setImageResource(R.drawable.ic_common_def_header);
	}
	
	Uri uri = null;
	//利用requestCode区别开不同的返回结果
	//resultCode参数对应于子模块中setResut(int resultCode, Intent intent)函数中的resultCode值，用于区别不同的返回结果（如请求正常、请求异常等）
	//对应流程：
	//母模块startActivityForResult--触发子模块，根据不同执行结果设定resucode值，最后执行setResut并返回到木模块--母模块触发onActivityResult，根据requestcode参数区分不同子模块。
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==2 && resultCode==2 && data!=null){
        	String filepath = data.getStringExtra("filepath");
        	Toast.makeText(PreferenceActivity.this, "filepath="+filepath, Toast.LENGTH_LONG).show();
			if(filepath.length() > 0){
//				sendFile(filepath);//P2P send file
				File file = new File(filepath);
				if (file.exists() && file.canRead()) {
					sendOfflineFile(filepath,"file");//send offline file via agent file server 
								    
				} else {
					Toast.makeText(PreferenceActivity.this, "file not exists", Toast.LENGTH_LONG).show();
				}
			}
        }
        else if ( requestCode == GalleryHelper.GALLERY_REQUEST_CODE) {
            if ( resultCode == GalleryHelper.GALLERY_RESULT_SUCCESS ) {
                PhotoInfo photoInfo = data.getParcelableExtra(GalleryHelper.RESULT_DATA);
                List<PhotoInfo> photoInfoList = (List<PhotoInfo>) data.getSerializableExtra(GalleryHelper.RESULT_LIST_DATA);

                if ( photoInfo != null ) {
//                    ImageLoader.getInstance().displayImage("file:/" + photoInfo.getPhotoPath(), mIvResult);
                    uri = Uri.parse("file:/" + photoInfo.getPhotoPath());
                    Toast.makeText(this, "选择了照片路径:" + photoInfo.getPhotoPath(), Toast.LENGTH_SHORT).show();
                    sendOfflineFile(photoInfo.getPhotoPath(),"img");
                }

                if ( photoInfoList != null ) {
                    Toast.makeText(this, "选择了" + photoInfoList.size() + "张", Toast.LENGTH_SHORT).show();
                }
            }
        }
        else if ( requestCode == GalleryHelper.TAKE_REQUEST_CODE ) {
            if (resultCode == RESULT_OK && mTakePhotoUri != null) {
                final String path = mTakePhotoUri.getPath();
                final PhotoInfo info = new PhotoInfo();
                info.setPhotoPath(path);
//                updateGallery(path);

                final int degress = BitmapUtils.getDegress(path);
                if (degress != 0) {
                    new com.beem.push.utils.AsyncTask<Void, Void, Void>() {

                        @Override
                        protected void onPreExecute() {
                            super.onPreExecute();
                            toast("请稍等…");
                        }

                        @Override
                        protected Void doInBackground(Void... params) {
                            try {
                                Bitmap bitmap = rotateBitmap(path, degress);
                                saveRotateBitmap(bitmap, path);
                                bitmap.recycle();
                            } catch (Exception e) {
                                Logger.e(e);
                            }
                            return null;
                        }

                        @Override
                        protected void onPostExecute(Void voids) {
                            super.onPostExecute(voids);
//                            takeResult(info);
                            toPhotoCrop(info);
                        }
                    }.execute();
                } else {
//                    takeResult(info);
                	toPhotoCrop(info);
                }
            } else {
                toast("拍照失败");
            }
        } else if ( requestCode == GalleryHelper.CROP_REQUEST_CODE) {
            if ( resultCode == GalleryHelper.CROP_SUCCESS ) {
                PhotoInfo photoInfo = data.getParcelableExtra(GalleryHelper.RESULT_DATA);
                resultSingle(photoInfo);
            }
        } else if ( requestCode == GalleryHelper.GALLERY_RESULT_SUCCESS ) {
            PhotoInfo photoInfo = data.getParcelableExtra(GalleryHelper.RESULT_DATA);
            List<PhotoInfo> photoInfoList = (List<PhotoInfo>) data.getSerializableExtra(GalleryHelper.RESULT_LIST_DATA);

            if ( photoInfo != null ) {
//                ImageLoader.getInstance().displayImage("file:/" + photoInfo.getPhotoPath(), mIvResult);
                uri = Uri.parse("file:/" + photoInfo.getPhotoPath());
                Toast.makeText(this, "选择了照片路径:" + photoInfo.getPhotoPath(), Toast.LENGTH_SHORT).show();
                sendOfflineFile(photoInfo.getPhotoPath(),"img");
            }

            if ( photoInfoList != null ) {
                Toast.makeText(this, "选择了" + photoInfoList.size() + "张", Toast.LENGTH_SHORT).show();
            }
        }
    }
    
  //recodeTime
    String transformfilepath = "";
    String transformfiletype = "";
    private void sendOfflineFile(String filepath,String type) {
		
    	transformfilepath = filepath;
    	transformfiletype = type;
    	
		try{
    		File file2 = new File(transformfilepath);
    		if(file2.exists()){
    			Bitmap bitmap = BitmapFactory.decodeFile(transformfilepath);
//    			setUserPhoto(bitmap);
    			upload(transformfilepath,"9999");
    			
    		}
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
    
    
    /**
     * 拍照
     */
    String mPhotoTargetFolder = null;
    Uri mTakePhotoUri = null;
    protected void takePhotoAction() {

        if (!DeviceUtils.existSDCard()) {
//            toast("没有SD卡不能拍照呢~");
        	Toast.makeText(this, "没有SD卡不能拍照呢~", Toast.LENGTH_SHORT).show();
            return;
        }

        File takePhotoFolder = null;
        if (cn.finalteam.toolsfinal.StringUtils.isEmpty(mPhotoTargetFolder)) {
            takePhotoFolder = new File(Environment.getExternalStorageDirectory(),
                    "/DCIM/" + GalleryHelper.TAKE_PHOTO_FOLDER);
        } else {
            takePhotoFolder = new File(mPhotoTargetFolder);
        }

        File toFile = new File(takePhotoFolder, "IMG" + DateUtils.format(new Date(), "yyyyMMddHHmmss") + ".jpg");
        boolean suc = FileUtils.makeFolders(toFile);
        Logger.d("create folder=" + toFile.getAbsolutePath());
        if (suc) {
            mTakePhotoUri = Uri.fromFile(toFile);
            Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mTakePhotoUri);
            startActivityForResult(captureIntent, GalleryHelper.TAKE_REQUEST_CODE);
        }
    }
    protected int mScreenWidth = 720;
    protected int mScreenHeight = 1280;
    protected Bitmap rotateBitmap(String path, int degress) {
        try {
            Bitmap bitmap = BitmapUtils.compressBitmap(path, mScreenWidth / 4, mScreenHeight / 4);
            bitmap = BitmapUtils.rotateBitmap(bitmap, degress);
            return bitmap;
        } catch (Exception e) {
            Logger.e(e);
        }

        return null;
    }

    protected void saveRotateBitmap(Bitmap bitmap, String path) {
        //保存
        BitmapUtils.saveBitmap(bitmap, new File(path));
        //修改数据库
        ContentValues cv = new ContentValues();
        cv.put("orientation", 0);
        ContentResolver cr = getContentResolver();
        String where = new String(MediaStore.Images.Media.DATA + "='" + cn.finalteam.toolsfinal.StringUtils.sqliteEscape(path) +"'");
        cr.update(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, cv, where, null);
    }
    public void toast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
    protected void resultSingle(PhotoInfo photoInfo) {
//        Intent intent = getIntent();
//        if (intent == null) {
//            intent = new Intent();
//        }
//        intent.putExtra(GalleryHelper.RESULT_DATA, photoInfo);
////        setResult(GalleryHelper.GALLERY_RESULT_SUCCESS, intent);
////        finish();
//        startActivityForResult(intent, GalleryHelper.GALLERY_RESULT_SUCCESS);
    	
        if ( photoInfo != null ) {
//          ImageLoader.getInstance().displayImage("file:/" + photoInfo.getPhotoPath(), mIvResult);
          uri = Uri.parse("file:/" + photoInfo.getPhotoPath());
          Toast.makeText(this, "选择了照片路径:" + photoInfo.getPhotoPath(), Toast.LENGTH_SHORT).show();
          sendOfflineFile(photoInfo.getPhotoPath(),"img");
      }
    }
    /**
     * 执行裁剪
     */
    protected void toPhotoCrop(PhotoInfo info) {
        Intent intent = new Intent(this, PhotoCropActivity.class);
        intent.putExtra(PhotoCropActivity.PHOTO_INFO, info);
        startActivityForResult(intent, GalleryHelper.CROP_REQUEST_CODE);
    }
    
    
    public void upload(String mPicPath,String fromAccount){
    	try{
            final File file = new File(mPicPath);  
            
            if (file != null) {  
//                String request = UploadUtil.uploadFile(file, requestURL);  
//                String uploadHost="http://10.0.2.2:9090/plugins/offlinefiletransfer/offlinefiletransfer";  
            	String uploadHost = XmppConnectionAdapter.uploadHost.replace("OfflinefiletransferServlet", "UploadHeadServlet");
            	uploadHost = "http://10.0.2.2:8080/thinkis/maps/Resource/uploadHead.jsp";
            	uploadHost = XmppConnectionAdapter.downloadPrefix + "/maps/Resource/uploadHead.jsp";
            	
//                RequestParams params=new RequestParams();  
////                params.addBodyParameter("msg",imgtxt.getText().toString());   
//                params.addBodyParameter(picPath.replace("/", ""), file);   
//                uploadMethod(params,uploadHost);
////                uploadImage.setText(request);  
                RequestParams params = new RequestParams();
//                params.addHeader("name", "value");
//                params.addHeader(HttpUtils.HEADER_ACCEPT_ENCODING, HttpUtils.ENCODING_GZIP);
                params.addHeader("Accept-Encoding", "gzip");
//                params.addQueryStringParameter("name", "value");
                params.addQueryStringParameter("fromAccount", CurrentUid);//代表存储目录fromAccount
//                SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
//        	    String uid = settings.getString("uidStr", "");
        	    params.addQueryStringParameter("uidStr", CurrentUid);
                params.addQueryStringParameter("sendType", "img");
                params.addQueryStringParameter("sendSize", "0");
                // 只包含字符串参数时默认使用BodyParamsEntity，
                // 类似于UrlEncodedFormEntity（"application/x-www-form-urlencoded"）。
//                params.addBodyParameter("fromAccount", fromAccount);
//                params.addBodyParameter("toAccount", toAccount);
//                params.addBodyParameter("sendType", "audio");
//                params.addBodyParameter("sendSize", (int) mRecord_Time+"");

                // 加入文件参数后默认使用MultipartEntity（"multipart/form-data"），
                // 如需"multipart/related"，xUtils中提供的MultipartEntity支持设置subType为"related"。
                // 使用params.setBodyEntity(httpEntity)可设置更多类型的HttpEntity（如：
                // MultipartEntity,BodyParamsEntity,FileUploadEntity,InputStreamUploadEntity,StringEntity）。
                // 例如发送json参数：params.setBodyEntity(new StringEntity(jsonStr,charset));
//                BodyParamsEntity bpe = new BodyParamsEntity();
//                bpe.addParameter("fromAccount", fromAccount);
//                bpe.addParameter("toAccount", toAccount);
//                bpe.addParameter("sendType", "audio");
//                bpe.addParameter("sendSize", (int) mRecord_Time+"");
//                params.setBodyEntity(bpe);
                params.addBodyParameter("file", file);
                uploadMethod(params,uploadHost);
                
            }  
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    }
    
	private HttpUtils http;
	private HttpHandler handler;
	
    //上传照片start
    public  void uploadMethod(final RequestParams params,final String uploadHost) {  
    	http = new HttpUtils();
    	http.configCurrentHttpCacheExpiry(1000 * 10); // 设置缓存10秒，10秒内直接返回上次成功请求的结果。
    	
    	handler = http.send(HttpRequest.HttpMethod.POST, uploadHost, params,new RequestCallBack<String>() {  
                    @Override  
                    public void onStart() {  
//                      msgTextview.setText("conn...");  
                      mHandler.sendEmptyMessage(4);
                    }  
                    @Override  
                    public void onLoading(long total, long current,boolean isUploading) {  
//                        if (isUploading) {  
//                          msgTextview.setText("upload: " + current + "/"+ total);  
//                        } else {  
//                          msgTextview.setText("reply: " + current + "/"+ total);  
//                        }  
    					android.os.Message message = mHandler.obtainMessage();
//    					message.arg1 = (int) (current*100/total);
    					message.arg1 = 80;//gzip 后 total为0
    					message.what = 1;
    		//								message.sendToTarget();
    					mHandler.sendMessage(message);
                    }  
                    public void onSuccess(ResponseInfo<String> responseInfo) { 
                    	Log.e("※※※※※####20140806####※※※※※", "※※上传成功"+responseInfo.statusCode+";reply: " + responseInfo.result);
                    	//statuscode == 200
//                      msgTextview.setText("statuscode:"+responseInfo.statusCode+";reply: " + responseInfo.result); 
                    	
                    	mHandler.sendEmptyMessage(2);
                    }  
                    public void onFailure(HttpException error, String msg) {  
//                      msgTextview.setText(error.getExceptionCode() + ":" + msg);  
                    	Log.e("※※※※※####20140806####※※※※※", "※※上传失败"+error.getExceptionCode() + ":" + msg);
                    	mHandler.sendEmptyMessage(3);
                    }  
                });  
        
    } 
    //上传照片end
    
    private  Dialog creatingProgress = null;
	private ProgressBar bar;
	private TextView progress;
	
	public void initialProgressDialog(){
		//创建处理进度条
		creatingProgress= new Dialog(PreferenceActivity.this,R.style.Dialog_loading_noDim);
		Window dialogWindow = creatingProgress.getWindow();
		WindowManager.LayoutParams lp = dialogWindow.getAttributes();
		lp.width = (int) (getResources().getDisplayMetrics().density*240);
		lp.height = (int) (getResources().getDisplayMetrics().density*80);
		lp.gravity = Gravity.CENTER;
		dialogWindow.setAttributes(lp);
		creatingProgress.setCanceledOnTouchOutside(false);//禁用取消按钮
		creatingProgress.setContentView(R.layout.activity_recorder_progress);
		
		progress = (TextView) creatingProgress.findViewById(R.id.recorder_progress_progresstext);
		bar = (ProgressBar) creatingProgress.findViewById(R.id.recorder_progress_progressbar);
	}
	
	//网络状态 start
	@Override
	public void connectionStatusChanged(int connectedState, String reason) {
		Log.e("MMMMM20140604MMMMMMMMMMMM", "++++++++++++++connectionStatusChanged0++++++++++++");
		switch (connectedState) {
		case 0://connectionClosed
			mHandler3.sendEmptyMessage(0);
			break;
		case 1://connectionClosedOnError
//			mConnectErrorView.setVisibility(View.VISIBLE);
//			mNetErrorView.setVisibility(View.VISIBLE);
//			mConnect_status_info.setText("连接异常!");
			mHandler3.sendEmptyMessage(1);
			break;
		case 2://reconnectingIn
//			mNetErrorView.setVisibility(View.VISIBLE);
//			mConnect_status_info.setText("连接中...");
			mHandler3.sendEmptyMessage(2);
			break;
		case 3://reconnectionFailed
//			mNetErrorView.setVisibility(View.VISIBLE);
//			mConnect_status_info.setText("重连失败!");
			mHandler3.sendEmptyMessage(3);
			break;
		case 4://reconnectionSuccessful
//			mNetErrorView.setVisibility(View.GONE);
			mHandler3.sendEmptyMessage(4);

		default:
			break;
		}
	}
	Handler mHandler3 = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				break;

			case 1:
				mNetErrorView.setVisibility(View.VISIBLE);
				if(BeemConnectivity.isConnected(mContext))
				mConnect_status_info.setText("连接异常!");
				break;

			case 2:
				mNetErrorView.setVisibility(View.VISIBLE);
				if(BeemConnectivity.isConnected(mContext))
				mConnect_status_info.setText("连接中...");
				break;
			case 3:
				mNetErrorView.setVisibility(View.VISIBLE);
				if(BeemConnectivity.isConnected(mContext))
				mConnect_status_info.setText("重连失败!");
				break;
				
			case 4:
				mNetErrorView.setVisibility(View.GONE);
				String udid = "";
				String partnerid = "";
				try{
					udid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().UDID;
					partnerid = mXmppFacade.getXmppConnectionAdapter().getMService().getPartnerid();
				}catch(Exception e){
					e.printStackTrace();
				}
//				udidTextView.setText("udid="+udid);
//				partneridEditText.setText(partnerid);
//				getContactList();//20141025 added by allen
				break;
			case 5:
				mNetErrorView.setVisibility(View.VISIBLE);
				mConnect_status_info.setText("当前网络不可用，请检查你的网络设置。");
				break;
			case 6:
				if(mXmppFacade!=null 
//						&& mXmppFacade.getXmppConnectionAdapter()!=null 
//						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null//&& !mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected()
//						&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
						&& BeemConnectivity.isConnected(mContext)){
					
				}else{
					mNetErrorView.setVisibility(View.VISIBLE);
					if(BeemConnectivity.isConnected(mContext))
					mConnect_status_info.setText("网络可用,连接中...");
				}
				break;	
			}
		}

	};
	private BroadcastReceiver mNetWorkReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();  
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {  
                Log.d("PoupWindowContactList", "网络状态已经改变");  
//                connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);  
//                info = connectivityManager.getActiveNetworkInfo();    
//                if(info != null && info.isAvailable()) {  
//                    String name = info.getTypeName();  
//                    Log.d(tag, "当前网络名称：" + name);  
//                    //doSomething()  
//                } else {  
//                    Log.d(tag, "没有可用网络");  
//                  //doSomething()  
//                }  
                if(BeemConnectivity.isConnected(context)){
//                	mNetErrorView.setVisibility(View.GONE);
//                	isconnect = 0;
                	mHandler3.sendEmptyMessage(6);//4
                }else{
//                	mNetErrorView.setVisibility(View.VISIBLE);
//                	isconnect = 1;
                	mHandler3.sendEmptyMessage(5);
                	Log.d("PoupWindowContactList", "当前网络不可用，请检查你的网络设置。");
                }
            } 
        }
	};
	
	private boolean phonestate = false;//false其他， true接起电话或电话进行时 
    /* 内部class继承PhoneStateListener */
    public class exPhoneCallListener extends PhoneStateListener
    {
        /* 重写onCallStateChanged
        当状态改变时改变myTextView1的文字及颜色 */
        public void onCallStateChanged(int state, String incomingNumber)
        {
          switch (state)
          {
            /* 无任何状态时 :说明没有拨打电话的界面的时候，也就是在拨打电话前和挂电话后的情况*/
            case TelephonyManager.CALL_STATE_IDLE:
            	Log.e("================20131216 无任何电话状态时================", "无任何电话状态时");
            	if(phonestate){
            		onPhoneStateResume();
            	}
            	phonestate = false;
              break;
            /* 接起电话时 :至少有一个电话存在、拨出或激活、接听，而没有一个电话在通话或等待的状态*/
            case TelephonyManager.CALL_STATE_OFFHOOK:
            	Log.e("================20131216 接起电话时================", "接起电话时");
            	onPhoneStatePause();
            	phonestate = true;
              break;
            /* 电话进来时 :在通话的过程中*/
            case TelephonyManager.CALL_STATE_RINGING:
//              getContactPeople(incomingNumber);
            	Log.e("================20131216 电话进来时================", "电话进来时");
//            	onBackPressed();
            	onPhoneStatePause();
            	phonestate = true;
              break;
            default:
              break;
          }
          super.onCallStateChanged(state, incomingNumber);
        }
    }
    
    protected void onPhoneStatePause() {
//		super.onPause();
    	try{
//    		try {
//    		    if (mRoster != null) {
//    			mRoster.removeRosterListener(mBeemRosterListener);
//    			mRoster = null;
//    		    }
//    		} catch (RemoteException e) {
//    		    Log.d("ContactList", "Remote exception", e);
//    		}
			if (mBinded) {
				getApplicationContext().unbindService(mServConn);
			    mBinded = false;
			}
			mXmppFacade = null;
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    }
    
    protected void onPhoneStateResume() {
//		super.onResume();
    	try{
		if (!mBinded){
//		    new Thread()
//		    {
//		        @Override
//		        public void run()
//		        {
		    mBinded = getApplicationContext().bindService(SERVICE_INTENT, mServConn, BIND_AUTO_CREATE);

//		        }
//		    }.start();		    
		}
		if (mBinded){
			mImageFetcher.setExitTasksEarly(false);
		}
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    }
    
    /*
     * 打开设置网络界面
     * */
    public static void setNetworkMethod(final Context context){
        //提示对话框
        AlertDialog.Builder builder=new AlertDialog.Builder(context);
        builder.setTitle("网络设置提示").setMessage("网络连接不可用,是否进行设置?").setPositiveButton("设置", new DialogInterface.OnClickListener() {
            
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                Intent intent=null;
                //判断手机系统的版本  即API大于10 就是3.0或以上版本 
                if(android.os.Build.VERSION.SDK_INT>10){
                    intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
                }else{
                    intent = new Intent();
                    ComponentName component = new ComponentName("com.android.settings","com.android.settings.WirelessSettings");
                    intent.setComponent(component);
                    intent.setAction("android.intent.action.VIEW");
                }
                context.startActivity(intent);
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                dialog.dismiss();
            }
        }).show();
    }
	//网络状态 end
}
